

var mongoose = require("mongoose");
var User = require('../modules/user.module');
var async=require('async');
var Usercommentr = require('../modules/usercomment.module');
exports.create = function(req, res, next) {
    console.log(req.body)
    const user = new User(req.body);

    user.save(function(err, data) {
        if (err) {
            console.log(err)
        } else {
            res.json(data);
        }
    })
}

exports.update = function(req, res, next) {
    const id = req.params.id;

    User.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
        res.json(data);
    });
};

exports.remove = function(req, res, next) {
    const id = req.params.id;

    User.findByIdAndRemove(id, function(err, data) {
        res.json({ 'message': 'delete ok' });
    });
};
exports.list = function(req, res, next) {
    var page = (req.body.page) ? req.body.page : 1;
    var limit = (req.body.limit) ? req.body.limit : 3;
    var queryCondition = {};
    if (req.body.name && req.body.name.trim().length) {
        name = req.body.name;
        queryCondition = {
            "name": new RegExp(name, "i")
        }
    }

    if (req.body._id) {
        _id = req.body._id;
        queryCondition = {
            "_id": _id
        }
    }
    User.paginate(queryCondition, { page: page, limit: limit }, function(err, results) {
       
      //  console.log(results)
        async.map(results.docs,function(user,done){
            Usercommentr.count({useid:user._id}).then(data=>{               
                
                user.number=data;console.log(user.number);
                done(null,user);
            })    
        },function(err){
            res.json(results);
        })
         

    })

}
exports.login = function(req, res, next) {
    console.log(req.body)
    var name = req.body.name;
    var password = req.body.password;
    User.findOne({ name: name, password: password }, function(err, doc) {
        console.log(doc)

        if (doc) {
            res.json(doc)
        } else {
            res.json({ 'massage': '用户名或者密码错误！' })
        }

    })

}